package com.xtayfjpk.security;

import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.SecretKeySpec;

import org.junit.Test;

/**
 * X509用于公钥编码格式
 * PKCS#8用于私钥编码格式
 * @author zj
 *
 */
public class KeySpecTest {
	
	@Test
	public void testX509() throws Exception {
		KeyPairGenerator generator = KeyPairGenerator.getInstance("DSA");
		generator.initialize(1024);
		
		KeyPair keyPair = generator.generateKeyPair();
		
		System.out.println(keyPair.getPublic().getFormat());
		byte[] encoded = keyPair.getPublic().getEncoded();
		X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(encoded);
		
		KeyFactory factory = KeyFactory.getInstance("DSA");
		PublicKey publicKey = factory.generatePublic(x509EncodedKeySpec);
		System.out.println(publicKey);
		System.out.println(keyPair.getPublic().equals(publicKey));
	}

	@Test
	public void testPKCS8() throws Exception {
		KeyPairGenerator generator = KeyPairGenerator.getInstance("DSA");
		generator.initialize(1024);
		
		KeyPair keyPair = generator.generateKeyPair();
		
		System.out.println(keyPair.getPrivate().getFormat());
		byte[] encoded = keyPair.getPrivate().getEncoded();
		PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(encoded);
		
		KeyFactory factory = KeyFactory.getInstance("DSA");
		PrivateKey privateKey = factory.generatePrivate(pkcs8EncodedKeySpec);
		System.out.println(privateKey);
		System.out.println(keyPair.getPrivate().equals(privateKey));
	}
	
	@Test
	public void testSecretKeySpec() throws Exception {
		KeyGenerator generator = KeyGenerator.getInstance("RC2");
		SecretKey secretKey = generator.generateKey();
		System.out.println(secretKey.getFormat());
		SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getEncoded(), "RC2");
		
		System.out.println(secretKeySpec instanceof SecretKey);
	}
	
	@Test
	public void testDESKeySpec() throws Exception {
		KeyGenerator generator = KeyGenerator.getInstance("DES");
		SecretKey secretKey = generator.generateKey();
		System.out.println(secretKey.getFormat());
		
		DESKeySpec desKeySpec = new DESKeySpec(secretKey.getEncoded());
		
		SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
		SecretKey key = factory.generateSecret(desKeySpec);
		System.out.println(key);
		System.out.println(secretKey.equals(key));
	}
}
